#include "tcp_receiver.hh"

using namespace std;

void TCPReceiver::receive( TCPSenderMessage message )
{
  // Your code here.
  const uint64_t checkpoint=reassembler_.writer().bytes_pushed()+ISN_.has_value();
  if(message.RST){
    reassembler_.reader().set_error();//链路出现问题，中断传输，因为是写入重组器，所以是reader
  }else if(checkpoint>0&&checkpoint<=UINT32_MAX&&message.seqno==ISN_)
    return;
  if(!ISN_.has_value()){
    if(!message.SYN)
      return;
    ISN_=message.seqno;
  }
  const uint64_t abs_seqn=message.seqno.unwrap(*ISN_,checkpoint);
  reassembler_.insert(abs_seqn==0?abs_seqn:abs_seqn-1,move(message.payload),message.FIN);
}

TCPReceiverMessage TCPReceiver::send() const
{
  // Your code here.
  const uint64_t checkpoint=reassembler_.writer().bytes_pushed()+ISN_.has_value();
  const uint64_t capc=reassembler_.writer().available_capacity();
  const uint16_t wnd_size=capc>UINT16_MAX?UINT16_MAX:capc;//为什么是16位的？
  if (!ISN_.has_value())
    return{{},wnd_size,reassembler_.writer().has_error()};
  return{Wrap32::wrap(checkpoint+reassembler_.writer().is_closed(),*ISN_),
          wnd_size,
          reassembler_.writer().has_error()};
}
